package javango.forms.fields;

import java.util.Map;

import org.apache.commons.lang.StringUtils;

import com.google.inject.Inject;

import javango.forms.widgets.WidgetFactory;

public abstract class NumberSelectField<T extends Number> extends javango.forms.fields.AbstractChoiceField<T,String> {

	@Inject
	public NumberSelectField(WidgetFactory widgetFactory) {
		super(widgetFactory);
	}
	
	protected abstract T convert(String value);
	
	public NumberSelectField<T> setChoices(Map<T, String> choices) {
		return (NumberSelectField<T>)super.setChoices(choices);
	}
	
	@Override
	public T clean(String value, Map<String, String> errors) {
		if (StringUtils.isEmpty(value)) {
			if (isRequired()) { 
				errors.put(getName(), REQUIRED_ERROR);
			} else if (isAllowNull()) {
				return null;
			}
		}
		
		try {
			return convert(value);
		} catch (NumberFormatException e) {
			errors.put(getName(), UNKNOWN_CHOICE_ERROR);
		}
		
		return null;
	}

//	public T get(Long key) {
//		// TODO Auto-generated method stub
//		return null;
//	}

}
